<?php

declare(strict_types=1);
/**
 * This file is part of habo_new_media.
 *
 * @link     https://www.berlen.cn/
 * @contact  tech@berlen.cn
 * @license  http://gitlab.rehou.cn/habo/habo_new_media/-/blob/master/README.md
 */
namespace app\service\fetch\ocean;

use app\enum\CommonEnum;
use app\enum\ConfigEnum;
use app\enum\OceanEnum;
use app\model\ClientAccountModel;
use app\model\OeAudiencePackageModel;
use app\service\client\AccountService;
use app\service\fetch\MediaInterface;
use app\service\fetch\MediaService;
use app\service\ocean\AdvertiserService;
use app\service\ocean\MaterialService;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\Model;

class AudiencePackageService extends MediaService implements MediaInterface
{
    /**
     * @var string 数据拉取key
     */
    protected const FETCH_KEY = ConfigEnum::CACHE_CONFIG[OceanEnum::LIST_CONFIG_LOCK_KEY]['audience_package'];

    /**
     * 获取定向信息.
     *
     * @param string $advertiserId 广告主id
     */
    public static function getAudiencePackage(string $advertiserId = ''): bool
    {
        try {
            // 获取账户信息
            $obj = AccountService::getAccountModel(0, $advertiserId);
            if (! $obj instanceof ClientAccountModel || ! $obj->getKey()) {
                return self::setError('账户数据不存在');
            }
            $page = 0;
            $audienceIds = [];
            while (true) {
                $result = self::getList($advertiserId, ++$page);
                if ($result === false) {
                    return false;
                }
                if (count($result['data']['audience_packages']) == 0) {
                    break;
                }
                foreach ($result['data']['audience_packages'] as $item) {
                    $item = array_merge($item, $item['audience']);
                    unset($item['audience'], $item['app_behavior_target']);

                    if (isset($item['action'])) {
                        $item = array_merge($item, $item['action']);
                        unset($item['action']);
                    }
                    $item = json_decode(str_replace(':null', ':""', json_encode($item)), true);
                    $data = [
                        'client_id' => $obj->getAttr('client_id'),
                        'advertiser_id' => $advertiserId,
                        'account_id' => $obj->getKey(),
                        'audience_package_id' => $item['audience_package_id'],
                        'name' => $item['name'],
                        'description' => $item['description'] ?? '',
                        'district' => $item['district'] ?? '',
                        'region_version' => $item['region_version'] ?? '',
                        'city' => $item['city'] ?? '',
                        'location_type' => $item['location_type'] ?? '',
                        'gender' => $item['gender'] ?? '',
                        'age' => $item['age'] ?? '',
                        'retargeting_tags' => $item['retargeting_tags'] ?? '',
                        'retargeting_tags_exclude' => $item['retargeting_tags_exclude'] ?? '',
                        'platform' => $item['platform'] ?? '',
                        'hide_if_exists' => $item['hide_if_exists'] ?? '',
                        'android_osv' => $item['android_osv'] ?? '',
                        'article_category' => $item['article_category'] ?? '',
                        'carrier' => $item['carrier'] ?? '',
                        'activate_type' => $item['activate_type'] ?? '',
                        'device_brand' => $item['device_brand'] ?? '',
                        'launch_price' => $item['launch_price'] ?? '',
                        'addtime' => $item['addtime'] ?? '',
                        'landing_type' => $item['landing_type'] ?? '',
                        'ac' => $item['ac'] ?? '',
                        'ios_osv' => $item['ios_osv'] ?? '',
                        'interest_action_mode' => $item['interest_action_mode'] ?? '',
                        'delivery_range' => $item['delivery_range'] ?? '',
                        'auto_extend_enabled' => $item['auto_extend_enabled'] ?? '',
                        'auto_extend_targets' => $item['auto_extend_targets'] ?? '',
                        'action_scene' => $item['action_scene'] ?? '',
                        'action_days' => $item['action_days'] ?? '',
                        'action_categories' => $item['action_categories'] ?? '',
                        'action_words' => $item['action_words'] ?? '',
                        'interest_categories' => $item['interest_categories'] ?? '',
                        'interest_words' => $item['interest_words'] ?? '',
                        'aweme_fan_behaviors' => $item['aweme_fan_behaviors'] ?? '',
                        'aweme_fan_categories' => $item['aweme_fan_categories'] ?? '',
                        'aweme_fan_accounts' => $item['aweme_fan_accounts'] ?? '',
                        'aweme_fans_numbers' => $item['aweme_fans_numbers'] ?? '',
                        'aweme_fan_time_scope' => $item['aweme_fan_time_scope'] ?? '',
                        'filter_aweme_abnormal_active' => $item['filter_aweme_abnormal_active'] ?? '',
                        'filter_aweme_fans_count' => $item['filter_aweme_fans_count'] ?? '',
                        'filter_own_aweme_fans' => $item['filter_own_aweme_fans'] ?? '',
                        'superior_popularity_type' => $item['superior_popularity_type'] ?? '',
                        'flow_package' => $item['flow_package'] ?? '',
                        'exclude_flow_package' => $item['exclude_flow_package'] ?? '',
                        'device_type' => $item['device_type'] ?? '',
                        'hide_if_converted' => $item['hide_if_converted'] ?? '',
                        'converted_time_duration' => $item['converted_time_duration'] ?? '',
                        'geolocation' => $item['geolocation'] ?? '',
                        'bind_info' => $item['bind_info'] ?? '',
                        'app_category' => $item['app_category'] ?? '',
                        'app_ids' => $item['app_ids'] ?? '',
                        'aweme_fan_categories_data' => $item['aweme_fan_categories_data'] ?? '',
                        'action_categories_data' => $item['action_categories_data'] ?? '',
                        'interest_categories_data' => $item['interest_categories_data'] ?? '',
                        'action_words_data' => $item['action_words_data'] ?? '',
                        'interest_words_data' => $item['interest_words_data'] ?? '',
                        'aweme_fan_accounts_data' => $item['aweme_fan_accounts_data'] ?? '',
                    ];
                    $model = self::getInfo($advertiserId, strval($item['audience_package_id']));
                    if (! $model instanceof OeAudiencePackageModel || ! $model->getKey()) {
                        (new OeAudiencePackageModel())->create($data);
                    } else {
                        (new OeAudiencePackageModel())->where('id', $model->getKey())->update($data);
                    }
                    //                    if (! $res) {
                    //                        throw new \Exception('保存信息出错');
                    //                    }
                    $audienceIds[] = $item['audience_package_id'];
                }
            }
            if ($audienceIds) {
                (new OeAudiencePackageModel())->where('advertiser_id', $advertiserId)
                    ->whereNotIn('audience_package_id', $audienceIds)
                    ->delete();
            }
            return true;
        } catch (\Exception $e) {
            return self::setError($e->getMessage());
        }
    }

    /**
     * 拉取信息.
     *
     * @param string $advertiserId 账户id
     * @param int $page 分页
     * @return bool|mixed|string
     */
    private static function getList(string $advertiserId = '', int $page = 1)
    {
        $token = AccountService::getToken(CommonEnum::OE_MEDIA, $advertiserId);
        if (! $token) {
            return self::setError('token获取失败');
        }
        $headers = MaterialService::getHeader($token);
        $params = [
            'advertiser_id' => $advertiserId,
            'page' => $page,
            'page_size' => OceanEnum::MAX_CUSTOM_MATERIAL_PAGE_SIZE,
        ];

        return AdvertiserService::getAudiencePackage($headers, $params);
    }

    /**
     * 获取信息.
     *
     * @param string $advertiserId 账户id
     * @param string $audiencePackageId 定向包id
     * @return null|array|mixed|Model|OeAudiencePackageModel
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    private static function getInfo(string $advertiserId = '', string $audiencePackageId = '')
    {
        $where = [
            ['audience_package_id', '=', $audiencePackageId],
            ['advertiser_id', '=', $advertiserId],
        ];

        return (new OeAudiencePackageModel())->where($where)->field(true)->find();
    }

    private static function getField(array $fields = [])
    {
    }
}
